package com.gs.m_my_goods

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.provider.MediaStore
import android.widget.ImageView
import android.widget.TextView
import androidx.core.widget.addTextChangedListener
import com.bumptech.glide.Glide
import com.gs.common.API
import com.gs.common.BaseCompatActivity
import com.gs.common.data.Good
import com.gs.common.global.GlobalVariables
import com.gs.common.util.ActionBarUtil
import com.gs.common.util.BitmapSizeCalculator
import com.gs.common.util.ToastUtil
import com.gs.common.util.UnderlineUtil
import com.gs.m_my_goods.databinding.AddOrUpdateLayoutBinding
import com.gs.m_my_goods.persistent.AddOrUpdatePersistent


class AddOrUpdateActivity : BaseCompatActivity(),
    AddOrUpdatePersistent.OnUploadPictureStateCallback,
    AddOrUpdatePersistent.OnAddGoodStateCallback {

    private lateinit var binding: AddOrUpdateLayoutBinding
    private val addOrUpdatePersistent by lazy { AddOrUpdatePersistent.getInstance(this) }
    private var mUpdateGood: Good? = null
    private var mAddGoodImgPath: String? = null
    private var mStateString: String? = null
    private var mGoodImg: Bitmap? = null

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = AddOrUpdateLayoutBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 自定义 action bar
        ActionBarUtil.setCustomActionBar(this, R.layout.add_or_update_actionbar_layout)

        // 设置返回按键
        val backBtn = findViewById<ImageView>(R.id.back_btn)
        backBtn.setOnClickListener {
            finish()
        }

        mStateString = intent.getStringExtra("state")

        // action bar title
        val actionBarTitle = findViewById<TextView>(R.id.action_bar_title)
        actionBarTitle.text = "${mStateString}商品"

        UnderlineUtil.onFocusChangeColor(
            arrayOf(binding.titleEdt, binding.detailTitleEdt, binding.countEdt, binding.priceEdt),
            arrayOf(
                binding.titleUnderline,
                binding.detailTitleUnderline,
                binding.countUnderline,
                binding.priceUnderline
            ),
            com.gs.common.R.color.light_green
        )

        binding.uploadImgTitle.text = "${mStateString}图片"
        binding.addOrUpdateGoodBtn.text = "${mStateString}商品"

        binding.titleEdt.addTextChangedListener {
            if (it?.length != null) {
                if (it.length > 9) {
                    it.delete(8, it.length)
                }
            }
        }
        binding.detailTitleEdt.addTextChangedListener {
            if (it?.length != null) {
                if (it.length < 19) {
                    binding.detailTitleEdt.setTextColor(resources.getColor(com.gs.common.R.color.red))
                } else {
                    binding.detailTitleEdt.setTextColor(resources.getColor(com.gs.common.R.color.black))
                }
            }
        }
        binding.countEdt.addTextChangedListener {
            val count = it?.toString()?.toIntOrNull()
            if (count != null && count <= 0) {
                binding.countEdt.setTextColor(resources.getColor(com.gs.common.R.color.red))
            } else {
                binding.countEdt.setTextColor(resources.getColor(com.gs.common.R.color.black))
            }
        }
        binding.priceEdt.addTextChangedListener {
            val price = it?.toString()?.toDoubleOrNull()
            if (price != null && price < 0.1) {
                binding.priceEdt.setTextColor(resources.getColor(com.gs.common.R.color.red))
            } else {
                binding.priceEdt.setTextColor(resources.getColor(com.gs.common.R.color.black))
            }
        }

    }

    override fun onStart() {
        super.onStart()
        if (mStateString == "修改") {
            // 获取要修改的商品信息
            val goodId = intent.getStringExtra("goodId")?.toIntOrNull() ?: return
            addOrUpdatePersistent.getGoodsById(goodId, object : AddOrUpdatePersistent.OnGetGoodsByIdStateCallback{
                override fun onGetGoodsByIdSuccess() {
                    mUpdateGood = GlobalVariables.updateGood
                    if (mUpdateGood == null) {
                        ToastUtil.showShortToast(this@AddOrUpdateActivity, "获取商品信息失败")
                        return
                    }
                    Glide.with(this@AddOrUpdateActivity).load("http://${API.IP}:${API.PORT}${mUpdateGood!!.picture_path}")
                        .into(binding.goodImg)
                    binding.titleEdt.setText(mUpdateGood!!.title)
                    binding.detailTitleEdt.setText(mUpdateGood!!.detail_title)
                    binding.countEdt.setText(mUpdateGood!!.count.toString())
                    binding.priceEdt.setText(mUpdateGood!!.price.toString())
                }

                override fun onGetGoodsByIdFailed() {
                    ToastUtil.showShortToast(this@AddOrUpdateActivity, "获取商品信息失败")
                }

            })
        }
    }

    override fun onResume() {
        super.onResume()
        binding.goodImg.setOnClickListener {
            selectImage()
        }
        binding.addOrUpdateGoodBtn.setOnClickListener {
            val imgPath = mAddGoodImgPath ?: mUpdateGood?.picture_path
            if (imgPath == null) {
                ToastUtil.showShortToast(this, "请上传图片")
                return@setOnClickListener
            }
            val goodTitle = binding.titleEdt.text
            if (goodTitle.isNullOrBlank()) {
                ToastUtil.showShortToast(this, "请填写标题")
                return@setOnClickListener
            }
            val goodDetailTitle = binding.detailTitleEdt.text
            if (goodDetailTitle.isNullOrBlank()) {
                ToastUtil.showShortToast(this, "请填写详细标题")
                return@setOnClickListener
            }
            if (goodDetailTitle.length < 19) {
                ToastUtil.showShortToast(this, "详细标题需要19个字以上")
                return@setOnClickListener
            }
            val goodCountText = binding.countEdt.text
            if (goodCountText.isNullOrBlank()) {
                ToastUtil.showShortToast(this, "请填写库存量")
                return@setOnClickListener
            }
            val goodCount = goodCountText.toString().toInt()
            if (goodCount <= 0) {
                ToastUtil.showShortToast(this, "库存量不能少于1件")
                return@setOnClickListener
            }
            val goodPriceText = binding.priceEdt.text
            if (goodPriceText.isNullOrBlank()) {
                ToastUtil.showShortToast(this, "请填写单价")
                return@setOnClickListener
            }
            val goodPrice = goodPriceText.toString().toDouble()
            if (goodPrice < 0.1) {
                ToastUtil.showShortToast(this, "单价不能低于0.1元")
                return@setOnClickListener
            }
            val loginUser = GlobalVariables.loginUser
            if (loginUser == null) {
                ToastUtil.showShortToast(this, "${mStateString}商品失败")
                return@setOnClickListener
            }
            addOrUpdatePersistent.addOrUpdateGood(
                mStateString ?: "添加",
                loginUser.userName,
                mUpdateGood?.id,
                goodTitle.toString(),
                goodDetailTitle.toString(),
                imgPath,
                goodPrice,
                goodCount,
                this
            )
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        GlobalVariables.addGoodImgPath = null
        GlobalVariables.updateGood = null
    }

    private fun selectImage() {
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        startActivityForResult(intent, REQUEST_IMAGE_CAPTURE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK && data != null) {
            val selectedImageUri = data.data
            if (selectedImageUri != null) {
                val inputStream = contentResolver.openInputStream(selectedImageUri)
                mGoodImg = BitmapFactory.decodeStream(inputStream)
                if (mGoodImg != null) {
                    addOrUpdatePersistent.uploadPicture(mGoodImg!!, this)
                    return
                }
            }
            ToastUtil.showShortToast(this, "上传图片失败")
        }
    }

    private fun revertGoodImg() {
        if (mStateString == "添加") {
            binding.goodImg.setImageDrawable(resources.getDrawable(R.drawable.upload_img_btn_bg))
        } else {
            if (mUpdateGood != null) {
                Glide.with(this).load("http://${API.IP}:${API.PORT}${mUpdateGood!!.picture_path}")
                    .into(binding.goodImg)
            }
        }
    }

    override fun onUpdatePictureSuccess() {
        Glide.with(this).load(mGoodImg).into(binding.goodImg)
        mAddGoodImgPath = GlobalVariables.addGoodImgPath
        ToastUtil.showShortToast(this, "上传图片成功")
    }

    override fun onUpdatePictureFailed() {
        revertGoodImg()
        ToastUtil.showShortToast(this, "上传图片失败")
    }

    override fun onPictureExceedSizeFailed() {
        revertGoodImg()
        ToastUtil.showShortToast(this, "文件大小不能超过1MB")
    }

    override fun onPictureNullPointerFailed() {
        revertGoodImg()
        ToastUtil.showShortToast(this, "文件名为空，不能正常获取文件类型")
    }

    override fun onAddGoodSuccess() {
        ToastUtil.showShortToast(this, "${mStateString}商品成功")
        this.finish()
    }

    override fun onAddGoodFailed() {
        ToastUtil.showShortToast(this, "${mStateString}商品失败")
    }

    override fun onNetworkError() {
        revertGoodImg()
        ToastUtil.showShortToast(this, "无法连接网络！")
    }

    override fun onServerError() {
        revertGoodImg()
        ToastUtil.showShortToast(this, "无法连接服务器！")
    }

    companion object {
        private const val REQUEST_IMAGE_CAPTURE = 1
    }
}

